import { computed, onMounted, ref } from "vue";
import configApi, {
  type ConfigItem,
  type ConfigCreatePayload,
  type ConfigUpdatePayload,
  type ConfigListResult
} from "@/api/system/config";
import { useListPage } from "@/composables/useListPage";
import { useDialog } from "@/composables/useDialog";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";

interface ConfigFilterForm {
  keyword: string;
  category: string;
  status: string;
}

const DEFAULT_FILTER: ConfigFilterForm = {
  keyword: "",
  category: "",
  status: ""
};

export function useSystemConfig() {
  const categories = ref<Array<string>>([]);
  const { openDialog } = useDialog();

  const statusOptions = [
    { label: "全部状态", value: "" },
    { label: "启用", value: "1" },
    { label: "停用", value: "0" }
  ];

  const {
    formState: filterForm,
    pagination,
    dataList,
    loading,
    onSearch,
    resetForm: resetFilterState,
    handlePageChange: rawHandlePageChange,
    handleSizeChange
  } = useListPage<ConfigFilterForm, ConfigItem, ConfigListResult>(
    {
      fetch: params => configApi.fetchList(params)
    },
    DEFAULT_FILTER,
    {},
    {
      responseAdapter: (response: ConfigListResult) => {
        categories.value = response?.categories ?? [];
        const pagination = response?.pagination ?? {
          total: 0,
          pageSize: 10,
          currentPage: 1
        };
        return {
          list: response?.list ?? [],
          total: Number(pagination.total ?? 0),
          pageSize: Number(pagination.pageSize ?? 10),
          currentPage: Number(pagination.currentPage ?? 1)
        };
      }
    }
  );

  const columns: TableColumnList = [
    { label: "配置键", prop: "config_key", width: 200, align: "left" },
    { label: "配置类型", prop: "value_type", width: 120, slot: "type" },
    {
      label: "配置值",
      prop: "config_value",
      minWidth: 260,
      align: "left",
      slot: "value"
    },

    { label: "状态", prop: "status", width: 120, slot: "status" },
    { label: "更新时间", prop: "update_time", width: 180 },
    {
      label: "操作",
      prop: "operation",
      width: 180,
      fixed: "right",
      slot: "operation"
    }
  ];

  const tableData = computed(() => dataList.value ?? []);

  const fetchConfigs = () => onSearch();
  const changePage = (page: number) => rawHandlePageChange(page);

  const handleSearch = () => {
    changePage(1);
  };

  const resetFilters = () => {
    resetFilterState();
    changePage(1);
  };

  const openEdit = (item: ConfigItem) => {
    openDialog(() => import("../components/edit-form.vue"), {
      title: `编辑配置 - ${item.config_key}`,
      props: {
        item,
        onSubmit: async (payload: ConfigUpdatePayload) => {
          await configApi.update(item.id, payload);
          message("配置更新成功", { type: "success" });
          fetchConfigs();
        }
      }
    });
  };

  const openCreate = () => {
    openDialog(() => import("../components/create-form.vue"), {
      title: "新增配置",
      width: "520px",
      props: {
        categories: categories.value.slice(),
        onSubmit: async (payload: ConfigCreatePayload) => {
          await configApi.create(payload);
          message("配置创建成功", { type: "success" });
          fetchConfigs();
        }
      }
    });
  };

  const handleDelete = async (item: ConfigItem) => {
    try {
      await ElMessageBox.confirm(
        `确认删除配置「${item.config_key}」吗？`,
        "删除确认",
        {
          type: "warning",
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      );
    } catch {
      return;
    }

    try {
      await configApi.remove(item.id);
      message("配置已删除", { type: "success" });
      fetchConfigs();
    } catch (error: any) {
      message(error?.message ?? "删除配置失败", { type: "error" });
    }
  };

  const isObjectValue = (value: ConfigItem["config_value"]) =>
    value !== null && typeof value === "object";

  const serialiseValue = (value: ConfigItem["config_value"]) => {
    if (value === null || value === undefined) return "";
    if (typeof value === "boolean") return value ? "true" : "false";
    if (typeof value === "object") {
      try {
        return JSON.stringify(value, null, 2);
      } catch {
        return String(value);
      }
    }
    return String(value);
  };

  const previewValue = (value: ConfigItem["config_value"]) => {
    const text = serialiseValue(value);
    if (!text) return "-";
    return text.length > 80 ? `${text.slice(0, 80)}…` : text;
  };

  const shouldExpandValue = (value: ConfigItem["config_value"]) => {
    if (isObjectValue(value)) return true;
    return serialiseValue(value).length > 80;
  };

  onMounted(() => {
    fetchConfigs();
  });

  return {
    filterForm,
    categories,
    pagination,
    tableData,
    columns,
    loading,
    fetchConfigs,
    handleSearch,
    resetFilters,
    handlePageChange: changePage,
    handleSizeChange,
    openCreate,
    openEdit,
    handleDelete,
    statusOptions,
    isObjectValue,
    serialiseValue,
    previewValue,
    shouldExpandValue
  };
}
